package com.atguigu.srb.core.controller.admin;

import com.alibaba.excel.EasyExcel;
import com.atguigu.srb.core.exception.Assert;
import com.atguigu.srb.core.exception.BusinessException;
import com.atguigu.srb.core.pojo.dto.ExcelDictDTO;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.result.R;
import com.atguigu.srb.core.result.ResponseEnum;
import com.atguigu.srb.core.service.DictService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

//@CrossOrigin
@RestController
@RequestMapping("/admin/core/dict")
@Api(tags = "后端的后台数据字典管理")
public class AdminDictController {

    @Autowired
    private DictService dictService;

    @ApiOperation(value = "根据上级的parentId数据字典的列表")
    @GetMapping("/listByParentId/{id}")
    public R listByParentId(@PathVariable("id")
                            @ApiParam(value = "父节点id",
                                    defaultValue = "1",
                                    example = "1",
                                    required = true)
                                    Long parentId) throws BusinessException {
        List<Dict> dictList = dictService.getChildrenByPID(parentId);
        Assert.notNull(dictList, ResponseEnum.ERROR);
        return R.ok().data("list", dictList);
    }


    @PostMapping("/import")
    @ApiOperation(value = "Excel批量导入数据字典")
    public R importBatchData(@RequestParam("file")
                             @ApiParam(value = "Excel文件", required = true)
                                     MultipartFile file) throws BusinessException {
        try {
            InputStream inputStream = file.getInputStream();
            dictService.importExcelData(inputStream);
            return R.ok().message("数据导入成功");
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException(ResponseEnum.UPLOAD_ERROR);
        }

    }

    /**
     * 文件下载（失败了会返回一个有部分数据的Excel）
     * <p>
     * 1. 创建excel对应的实体对象 参照{@link ExcelDictDTO}
     * <p>
     * 2. 设置返回的 参数
     * <p>
     * 3. 直接写，这里注意，finish的时候会自动关闭OutputStream,当然你外面再关闭流问题不大
     */
    @ApiOperation("Excel文件下载")
    @GetMapping("/export")
    public void download(HttpServletResponse response) throws Exception {
        try {
            // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("myDict", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            List<ExcelDictDTO> dataList = null;

            dataList = dictService.listDictData();
            EasyExcel.write(
                    response.getOutputStream(),
                    ExcelDictDTO.class)
                    .sheet("数据字典")
                    .doWrite(dataList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
